package com.hongfeng.support.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.hongfeng.support.annotation.Online;
import com.hongfeng.support.common.Constants;
import com.hongfeng.support.common.Page;
import com.hongfeng.support.controller.common.BaseController;
import com.hongfeng.support.item.OrderItem;
import com.hongfeng.support.item.ParmItem;
import com.hongfeng.support.item.tag.FieldOperator;
import com.hongfeng.support.item.tag.LogicOperator;
import com.hongfeng.support.model.Menu;
import com.hongfeng.support.model.Purview;
import com.hongfeng.support.model.Role;
import com.hongfeng.support.model.User;
import com.hongfeng.support.service.MenuService;
import com.hongfeng.support.service.PurviewService;
import com.hongfeng.support.util.WebHelper;
import com.hongfeng.support.util.json.JsonUtils;

/**
 * 菜单Controller
 * 
 * @author llc
 * 
 */
@Controller
@Online
public class MenuController extends BaseController {

	@Resource
	private MenuService menuService;
	@Resource
	private PurviewService purviewService;

	@RequestMapping("list")
	public void list(HttpServletRequest request, HttpServletResponse response,
			String menuName, Page<Menu> page) throws Exception {
		log.info("查询菜单名：" + menuName);
		OrderItem order = new OrderItem("pid");
		ParmItem parm = new ParmItem("menuName", menuName, FieldOperator.LIKE);
		menuService.findPageByQuery(page, Menu.class, parm, order);
		Menu parentMenu = null;
		List<Menu> menus = page.getData();
		for (Menu menu : menus) {
			if (menu.getPid() != null) {
				long pid = menu.getPid().longValue();
				if (parentMenu == null || pid != parentMenu.getId().longValue()) {
					parentMenu = this.menuService.read(menu.getPid());
				}
				menu.setParentMenu(parentMenu);
			}
		}
		String json = JsonUtils.bean2Json(page, "pageSize", "pageIndex",
				"pageCount", "indexNumber");
		log.info("菜单信息：" + json);
		this.sendSuccResponse(response, json);
	}

	@RequestMapping("listAll")
	public void listAll(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("加载所有菜单");
		List<Menu> menus = menuService.findAll();
		String json = JsonUtils.array2Json(menus, "parentMenu");
		log.info("菜单信息：" + json);
		this.sendSuccResponse(response, json);
	}

	@RequestMapping("tree")
	public void tree(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "isAddHead", required = false) String isAddHead)
			throws Exception {
		log.info("是否要加头：" + isAddHead);
		List<Menu> menus = menuService.findAll();
		if (menus != null) {
			boolean b = isAddHead != null || "true".equals(isAddHead) ? true
					: false;
			String json = JsonUtils.treeJson(menus, b);
			log.info("菜单信息：" + json);
			this.sendSuccResponse(response, json);
		} else {
			this.sendErrorResponse(response, "加载菜单失败。");

		}
	}

	/**
	 * 
	 * <首页左侧菜单树>
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 *             void
	 * @see
	 * @throws
	 */
	@RequestMapping("left")
	public void left(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		User user = WebHelper.getSessionAttribute(request,
				Constants.SESSION_LOGIN_USER);
		Role role = user.getRole();
		ParmItem item = new ParmItem("role.id", role.getId(),
				FieldOperator.EQUAL);
		List<Purview> purviews = purviewService.findAllByQuery(Purview.class,
				item);
		List<Menu> menus = null;
		if (purviews != null) {
			menus = new ArrayList<Menu>();
			for (Purview purview : purviews) {
				Menu menu = purview.getMenu();
				if (menu.getPid() != null) {
					Menu pMenu = menuService.read(menu.getPid());
					menu.setParentMenu(pMenu);
				}
				menus.add(menu);
			}
			String json = JsonUtils.loadMenuTree(menus);
			log.info("菜单信息：" + json);
			this.sendSuccResponse(response, json);
		} else {
			this.sendErrorResponse(response, "加载菜单失败。");
		}
	}

	@RequestMapping("create")
	public void create(HttpServletRequest request,
			HttpServletResponse response, @RequestParam("menu") String menuJson) {
		log.info("添加菜单:" + (menuJson != null ? menuJson : null));
		if (menuJson == null) {
			this.sendErrorResponse(response, "菜单信息不能为空!");
			return;
		}
		Menu menu = (Menu) JsonUtils.json2Object(menuJson, Menu.class);
		List<ParmItem> items = new ArrayList<ParmItem>(2);
		items.add(new ParmItem("menuCode", menu.getMenuCode(),
				FieldOperator.EQUAL));
		items.add(new ParmItem("menuName", menu.getMenuName(),
				FieldOperator.EQUAL, LogicOperator.OR));
		List<Menu> menus = menuService.findAllByQuery(Menu.class, items);
		log.info("查询菜单结果：" + menus.size());
		if (menus.size() == 0) {
			if (menu.getPid() != null && menu.getPid().longValue() == 0) {
				menu.setPid(null);
			}
			menuService.create(menu);
		} else {
			this.sendErrorResponse(response, "菜单编码或菜单名称已存在。");
		}
	}

	@RequestMapping("update")
	public void update(HttpServletRequest request,
			HttpServletResponse response, @RequestParam("menu") String menuJson) {
		log.info("修改菜单:" + (menuJson != null ? menuJson : null));
		if (menuJson == null) {
			this.sendErrorResponse(response, "菜单信息不能为空。");
			return;
		}
		Menu menu = (Menu) JsonUtils.json2Object(menuJson, Menu.class);
		Menu tMenu = menuService.read(menu.getId());
		List<Menu> menus = null;
		if (!menu.getMenuCode().equals(tMenu.getMenuCode())) {
			ParmItem item = new ParmItem("menuCode", menu.getMenuCode(),
					FieldOperator.EQUAL);
			menus = menuService.findAllByQuery(Menu.class, item);
		} else if (!menu.getMenuName().equals(tMenu.getMenuName())) {
			ParmItem item = new ParmItem("menuName", menu.getMenuName(),
					FieldOperator.EQUAL);
			menus = menuService.findAllByQuery(Menu.class, item);
		}
		if (menus == null || menus.size() == 0) {
			Long pid = menu.getPid();
			if (pid != null && pid.longValue() > 0) {
				Menu pm = menuService.read(menu.getPid());
				Long menuId = menu.getId();
				Long pmPid = pm.getPid();
				if (pmPid != null && menuId.longValue() == pmPid.longValue()) {
					this.sendErrorResponse(response, "【" + pm.getMenuName()
							+ "】是【" + menu.getMenuName() + "】子菜单。");
					return;
				}
			}
			if (pid != null && pid.longValue() == 0) {
				menu.setPid(null);
			}
			menu.setCreateTime(tMenu.getCreateTime());
			menu.setCreator(tMenu.getCreator());
			menuService.update(menu);
		} else {
			this.sendErrorResponse(response, "菜单编码或菜单名称已存在。");
		}
	}

	@RequestMapping("read")
	public void read(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("id") Long id) throws Exception {
		log.info("读取菜单:" + id);
		Menu menu = menuService.read(id);
		String json = JsonUtils.bean2Json(menu);
		log.info("菜单信息：" + json);
		this.sendSuccResponse(response, json);
	}

	@RequestMapping("delete")
	public void delete(HttpServletRequest request,
			HttpServletResponse response, @RequestParam("ids") String ids)
			throws Exception {
		log.info("删除菜单:" + (ids != null ? ids.toString() : null));
		if (ids == null || "".equals(ids)) {
			this.sendErrorResponse(response, "请选择要删除的菜单！");
			return;
		}
		menuService.deleteMenuWithRelation(ids);
	}
}
